<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

use yii\base\ExitException;

/**
 * 地区服务类
 * @auther 荒
 * @since 1.0.0
 * @datetime 2023.10.25 17:00
 */
class RegionService
{
    /**
     * 获取指定筛选条件下的地区名
     * @param array $andFilterWhere 筛选条件
     * @return array
     */
    public static function getNamesByPid($andFilterWhere = [])
    {
        return Region::query(['name'])->where(['status' => 1])->andFilterWhere($andFilterWhere)->orderBy(['sort' => SORT_DESC, 'id' => SORT_ASC])->indexBy('name')->column();
    }

    /**
     * 级联动：通过地区名获取下一级列表
     * @param string $name 名称
     * @param int $level 级数
     * @return array
     */
    public static function getCascadeByName($name, $level = 1)
    {
        /** @var Region $regionModel */
        try {
            $regionModel = Region::findOneThrowEmptyException(['name' => $name, 'level' => $level]);
        } catch (ExitException $exitException) {
            throw $exitException;
        } catch (\Throwable $e) {
            return [];
        }

        return self::getCascadeByPid($regionModel->id);
    }

    /**
     * 级联动：通过PID获取下一级列表
     * @param int $pid 父ID
     * @return array
     */
    public static function getCascadeByPid($pid)
    {
        $all = Region::query(['name', 'status'])->where(['pid' => $pid])->orderBy(['sort' => SORT_DESC, 'id' => SORT_ASC,])->all();
        $result = [];
        foreach ($all as $item) {
            $result[] = ['value' => $item['name'], 'text' => $item['name'], 'disabled' => !$item['status']];
        }

        return $result;
    }
}